package whu.cn.whushare.ui.main.my;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.androidplus.util.ViewMapping;
import com.androidplus.util.ViewMappingUtil;
import com.dd.processbutton.iml.ActionProcessButton;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

import whu.cn.whushare.R;
import whu.cn.whushare.common.Constants;
import whu.cn.whushare.common.ImageWorkerManager;
import whu.cn.whushare.net.DownloadParams;
import whu.cn.whushare.net.Downloader;
import whu.cn.whushare.ui.common.BaseActivity;
import whu.cn.whushare.ui.common.LoadingHelper;
import whu.cn.whushare.ui.main.known.AddAnswerActivity;
import whu.cn.whushare.ui.main.known.AnswerDetailActivity;
import whu.cn.whushare.ui.main.known.InviteAnswerActivity;
import whu.cn.whushare.ui.main.known.QuestionDetailActivity;
import whu.cn.whushare.ui.main.known.adapter.AllQuestionListAdapter;
import whu.cn.whushare.ui.main.known.adapter.AnswerListAdapter;
import whu.cn.whushare.ui.main.known.adapter.TopicAdapter;
import whu.cn.whushare.ui.main.known.bean.AllQuestion;
import whu.cn.whushare.ui.main.known.bean.AnswerWrapBean;
import whu.cn.whushare.ui.main.known.bean.FavorBean;
import whu.cn.whushare.ui.main.known.bean.QuestionDetail;
import whu.cn.whushare.ui.main.known.bean.Topic;
import whu.cn.whushare.ui.main.my.adapter.TopicAllQuestionAdapter;
import whu.cn.whushare.util.SetOnClickUtil;
import whu.cn.whushare.util.Utils;

/**
 * Created by xiaoping on 2015/4/22.
 */
@ViewMapping(id=R.layout.activity_my_topic_detail)
public class MyTopicDetailActivity extends BaseActivity {
    @ViewMapping(id = R.id.topic_name)
    private TextView mTopicName;
    @ViewMapping(id = R.id.favor_btn)
    private ActionProcessButton mFavorBtn;
    @ViewMapping(id=R.id.topic_image)
    private ImageView mTopicImage;
    @ViewMapping(id = R.id.question_list)
    private PullToRefreshListView mQuestionListView;
    private TopicAllQuestionAdapter adapter;
    private List<AllQuestion> allQuestions = new ArrayList<>();
    private LoadingHelper mQuestionLoadingHelper;
    private boolean mHasQustionInited=false;
    private boolean mIsFavored;
    private int mCurrentPage=1;
    private String mQuestionId;
    private String topicName;
    private String topicId;
    private String topicImage;


    public static Intent getStartIntent(Context context,String topicName,String topicImage,String topicId) {
        Intent i = new Intent(context, MyTopicDetailActivity.class);
        i.putExtra("topicName", topicName);
        i.putExtra("topicImage",topicImage);
        i.putExtra("topicId",topicId);
        return i;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getIntentData();
        initView();


    }

    private void getIntentData() {
        if (getIntent() != null) {
            topicId = getIntent().getStringExtra("topicId");
            topicName = getIntent().getStringExtra("topicName");
            topicImage = getIntent().getStringExtra("topicImage");
        }
    }

    private void initView() {
        View root = ViewMappingUtil.mapView(this, this);
        SetOnClickUtil.registerOnClick(this);
        getTopBar(root);
        mTopBar.title.setText("话题详情");

        initLoadingHelper();
        mTopicName.setText(topicName);
        if (!TextUtils.isEmpty(topicImage)) {
            ImageWorkerManager.getInstance(this).loadCommonImage(Utils.getPhotoUrl(topicImage),
                    mTopicImage, R.drawable.avatar, R.drawable.avatar);
        }
        mFavorBtn.setMode(ActionProcessButton.Mode.ENDLESS);
        initQuestionListView();
    }

    private void initQuestionListView() {

        mQuestionListView.setMode(PullToRefreshBase.Mode.BOTH);
        mQuestionListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> listViewPullToRefreshBase) {
                getQuestionList(1);
                Utils.resetRefreshLabel(MyTopicDetailActivity.this, mQuestionListView);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> listViewPullToRefreshBase) {
                if (allQuestions.size() >= mTotal) {
                    Utils.setRefreshLabelToLast(MyTopicDetailActivity.this, mQuestionListView);
                    Utils.COMMON_HANDLER.sendMessageDelayed(
                            Message.obtain(Utils.COMMON_HANDLER, Utils.REFRESH_TO_COMPLETE, mQuestionListView), 500);
                } else {
                    getQuestionList(++mCurrentPage);
                }
            }
        });
        mQuestionListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                AllQuestion allQuestion = (AllQuestion) adapter.getItem(arg2 - 1);
                mQuestionId = String.valueOf(allQuestion.getQuestion().getId());
                startActivityForResult(QuestionDetailActivity.getStartIntent(MyTopicDetailActivity.this, mQuestionId), 1);
            }
        });
    }

    private void initLoadingHelper() {

        mQuestionLoadingHelper = new LoadingHelper(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getQuestionList(mCurrentPage);
            }
        });
        mQuestionLoadingHelper.onCreateView(LayoutInflater.from(this), mQuestionListView);
        getQuestionList(mCurrentPage);
    }




    @Override
    @SuppressWarnings("unchecked")
    public <T> void onSuccess(DownloadParams.PARSING_TYPE type, T response, Object obj) {
        super.onSuccess(type, response, obj);

        switch (type) {
            case MY_TOPIC_DETAIL:
                mCurrentPage = (int) obj;

                List<AllQuestion> questions = (List<AllQuestion>) response;

                if (adapter == null || mCurrentPage== 1) {
                    allQuestions = questions;

                    adapter = new TopicAllQuestionAdapter(this,allQuestions);
                    mQuestionListView.setAdapter(adapter);
                } else {
                    allQuestions.addAll(questions);
                    adapter.notifyDataSetChanged();
                }

                mHasQustionInited = true;
                mQuestionLoadingHelper.showContentView();
                mQuestionListView.onRefreshComplete();


                break;

            case FAVOR1:
                FavorBean favorBean = (FavorBean) response;
                mIsFavored = favorBean.type.equals("add");
                processBtnEnd();

                break;


            default:
                break;
        }
    }



    private void getQuestionList(int page) {
        mQuestionLoadingHelper.showLoadingView(mHasQustionInited);
        Downloader.getInstance(this).getTopicQuestionList(topicId,page,this,page);
    }



    @Override
    public void onFail(DownloadParams.PARSING_TYPE type, VolleyError error) {
        super.onFail(type, error);
        switch (type) {

            case MY_TOPIC_DETAIL:
                if (!mHasQustionInited) {
                    mQuestionLoadingHelper.showRetryView();
                }
                mQuestionListView.onRefreshComplete();
                break;
            case FAVOR1:
                if (TextUtils.isEmpty(msg)) {
                    toast(mIsFavored ? "取消关注失败" : "关注失败");
                } else {
                    toast(msg);
                }
                processBtnEnd();
                break;

            default:
                break;
        }
    }

    private void processBtnEnd() {
        mFavorBtn.setProgress(100);
        mFavorBtn.setText(mIsFavored ? "取消关注" :"关注");
        mFavorBtn.setEnabled(true);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.favor_btn:
                mFavorBtn.setEnabled(false);
                requestFavorQuestion();
                break;
            default:
                break;

        }
    }

    private void requestFavorQuestion() {
        Downloader.getInstance(this).requestFavorTopic(topicId,this);
        mFavorBtn.setProgress(50);
    }



}















































































































































































































































































































